package ru.ruchin.tek.employees.web;

import java.util.Map;
import javax.servlet.ServletContext;
import ru.ruchin.tek.employees.data.Department;
import ru.ruchin.tek.employees.data.Employee;
import ru.ruchin.tek.employees.data.EmployeeStorage;

/**
 *
 * @author yruchin
 */
class SaveObjectQueryHandler implements QueryHandler {
    @Override
    public String handleQuery(Map<String, String[]> query, ServletContext context) {        
        EmployeeStorage es = (EmployeeStorage)context.getAttribute(EmployeeStorage.CONTEXT_KEY);

        Employee employee = null;
        String[] id = query.get("id");

        if (id != null && !"".equals(id[0])) {
            employee = es.getEmployeeById(Long.parseLong(id[0]));
            employee.setEmail(query.get("email")[0]);
            employee.setFirstName(query.get("firstName")[0]);
            employee.setLastName(query.get("lastName")[0]);
            es.updateEmployee(employee);
        } else {
            String departmentId = query.get("dep_id")[0];
            Department d = es.getDepartmentById(Long.parseLong(departmentId));

            if (d == null) {
                return null;
            }

            employee = new Employee();
            employee.setEmail(query.get("email")[0]);
            employee.setFirstName(query.get("firstName")[0]);
            employee.setLastName(query.get("lastName")[0]);
            employee.setDepartment(d);
            es.updateEmployee(employee);
        }
 
        return "";
    }
}
